package org.goldfish.cookied_chatroom02.servlet;

import jakarta.servlet.RequestDispatcher;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.goldfish.cookied_chatroom02.entity.UserBean;
import org.goldfish.cookied_chatroom02.model.LoginManager;
import org.goldfish.cookied_chatroom02.model.LoginManagerImpl;
import org.goldfish.cookied_chatroom02.model.LoginParams;

import java.io.IOException;

@WebServlet(name = "login", value = "/")
public class LoginServlet extends HttpServlet implements LoginParams {
    LoginManager manager;

    @Override
    public void init() {
        manager = new LoginManagerImpl();
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        UserBean cookiedBean = manager.getUserBeanFromCookies(request.getCookies());
        if (cookiedBean != null)
            manager.writeUserBeanToRequestAttr(request, cookiedBean);
        manager.login(request).forward(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        UserBean bean = manager.getUserBeanFromPostInputStream(request.getInputStream());
        manager.chat(request);
        RequestDispatcher dispatcher;
        TRY:
        {
            Boolean isNewUser = manager.userNewToDB(bean);
            if (isNewUser == null) {
                manager.warn("数据库连接失败", request);
                dispatcher = manager.login(request);
                break TRY;
            }
            if (isNewUser) {
                manager.warn("用户不存在", request);
                dispatcher = manager.login(request);
                break TRY;
            }
            if (!manager.writeUserBeanToCookie(response, bean)) {
                manager.warn("保存用户信息失败", request);
            }
            manager.writeUserBeanToSession(request, bean);
            if (manager.isLoggedIn(request.getSession(), this)) {
                manager.warn("用户已登录", request);
            } else if (!manager.addLoggedIn(this, request)) {
                manager.warn("我们暂时无法保存登录信息", request);
            }

            response.sendRedirect("chat");
            return;
        }
        dispatcher.forward(request, response);
    }


}
